﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _7DaysToDieTools.Class;
using System.IO;

namespace _7DaysToDieTools
{
    public partial class FormStack : Form
    {
        #region 公共变量
        List<StackItem> StackItems = null;
        List<StackItem> StackItemsF = null;
        #endregion

        #region 初始化
        public FormStack()
        {
            InitializeComponent();
        }
        public FormStack(Form pForm)
        {
            InitializeComponent();
            this.Location = new Point(pForm.Location.X + pForm.Width / 2 - this.Width / 2, pForm.Location.Y + pForm.Height / 2 - this.Height / 2);
        }

        private void FormStack_Load(object sender, EventArgs e)
        {
            lvList.FullRowSelect = true;
        }

        private void FormStack_Shown(object sender, EventArgs e)
        {
            //检测文件
            string tmp = "";
            if (!CheckFile(out tmp))
            {
                MessageBox.Show(tmp);
                this.Close();
            }
            //初始化选择框
            if (cboxFilter.Items.Count > 0)
            {
                cboxFilter.SelectedIndex = 0;
            }
            else
            {
                cboxFilter.SelectedIndex = -1;
            }
            SetStatus(0);
        }
        #endregion

        #region 方法集

        /// <summary>
        /// 检测要修改的文件是否存在
        /// </summary>
        /// <param name="Msg">返回信息</param>
        /// <returns>是否存在</returns>
        private bool CheckFile(out string Msg)
        {
            Msg = "";
            FileInfo fi = null;
            try
            {
                fi = new FileInfo(Sinfo.Path.Config+Sinfo.File.Items);
                if (!fi.Exists)
                {
                    Msg = "找不到items.xml文件！";
                    return false;
                }
                fi = new FileInfo(Sinfo.Path.Config + Sinfo.File.Blocks);
                if (!fi.Exists)
                {
                    Msg = "找不到blocks.xml文件！";
                    return false;
                }
                return true;
            }
            catch (Exception x)
            {
                Msg = x.Message;
                return false;
            }
        }

        /// <summary>
        /// 加载数据到变量
        /// </summary>
        private void LoadData()
        {
            StackItems = StackAction.LoadStackItems();
        }

        /// <summary>
        /// 显示数据
        /// </summary>
        private void ShowData()
        {
            CheckAndSaveItem();
            if (StackItems == null)
            {
                return;
            }
            StackItemsF = new List<StackItem>();
            StackItemsF = StackItems.ToList<StackItem>();
            if (ckboxHaveStack.Checked)
            {
                foreach (StackItem item in StackItemsF.Where(S => S.StackNum == "0").ToList<StackItem>())
                {
                    StackItemsF.Remove(item);
                }
            }
            if (!ckboxBlocks.Checked)
            {
                foreach (StackItem item in StackItemsF.Where(S => S.Stacktype == StackType.Block).ToList<StackItem>())
                {
                    StackItemsF.Remove(item);
                }
            }

            if (!ckboxItems.Checked)
            {
                foreach (StackItem item in StackItemsF.Where(S => S.Stacktype == StackType.Item).ToList<StackItem>())
                {
                    StackItemsF.Remove(item);
                }
            }
            if (!string.IsNullOrWhiteSpace(tboxFilter.Text))
            {
                if (cboxFilter.SelectedIndex == 0)
                {
                    foreach (StackItem item in StackItemsF.Where(S => !S.Name.ToLower().Contains(tboxFilter.Text.ToLower())).ToList<StackItem>())
                    {
                        StackItemsF.Remove(item);
                    }
                }
                else if (cboxFilter.SelectedIndex == 1)
                {
                    foreach (StackItem item in StackItemsF.Where(S => !S.ID.ToLower().Contains(tboxFilter.Text.ToLower())).ToList<StackItem>())
                    {
                        StackItemsF.Remove(item);
                    }
                }
                else if (cboxFilter.SelectedIndex == 2)
                {
                    foreach (StackItem item in StackItemsF.Where(S => !S.IDName.ToLower().Contains(tboxFilter.Text.ToLower())).ToList<StackItem>())
                    {
                        StackItemsF.Remove(item);
                    }
                }
            }


            lvList.VirtualListSize = StackItemsF.Count;
            //MessageBox.Show("总数："+StackItems.Count.ToString()+":显示数："+StackItemsF.Count.ToString());
            ClearMessage();
            lvList.Refresh();
        }

        /// <summary>
        /// 清空界面信息
        /// </summary>
        private void ClearMessage()
        {
            tboxEID.Clear();
            tboxEType.Clear();
            tboxEIDName.Clear();
            tboxEName.Clear();
            tboxESStack.Clear();
            numEDStack.Value = 0;

        }

        /// <summary>
        /// 检测并保存修改项
        /// </summary>
        private void CheckAndSaveItem()
        {
            //检测当前项是否更改
            if (!String.IsNullOrWhiteSpace(tboxEID.Text))
            {
                if (numEDStack.Value.ToString() != tboxESStack.Text)
                {
                    StackItems.Where(S => S.ID == tboxEID.Text).ToList<StackItem>()[0].StackNum = numEDStack.Value.ToString();
                }
            }
        }

        /// <summary>
        /// 设置界面状态
        /// 0:默认
        /// 1:已加载文件
        /// </summary>
        /// <param name="state">状态代码</param>
        private void SetStatus(int state)
        {
            if (state == 0)
            {
                //主按钮
                buttLoad.Visible = true;
                buttClose.Visible = false;
                buttSave.Visible = false;

                
                gboxFilter.Enabled = false;
                panelStackEdit.Enabled = false;
                gboxLoadShift.Enabled = false;
            }
            else if(state==1)
            {
                //主按钮
                buttLoad.Visible = false;
                buttClose.Visible = true;
                buttSave.Visible = true;

                gboxFilter.Enabled = true;
                panelStackEdit.Enabled = true;
                gboxLoadShift.Enabled = true;
            }
        }
        #endregion

        #region 主按钮
        private void buttLoad_Click(object sender, EventArgs e)
        {
            //加载数据
            lvList.VirtualListSize = 0;
            LoadData();
            ShowData();
            SetStatus(1);
        }

        private void buttClose_Click(object sender, EventArgs e)
        {
            ClearMessage();
            lvList.VirtualListSize = 0;
            StackItems.Clear();
            StackItemsF.Clear();
            SetStatus(0);
        }

        private void buttSave_Click(object sender, EventArgs e)
        {
            CheckAndSaveItem();
            string tmp = "";
            if (StackAction.SaveStackItems(StackItems, out tmp))
            {
                MessageBox.Show("保存成功！");
                SetStatus(1);
            }
            else
            {
                MessageBox.Show("保存失败！因为：\n" + tmp);
            }
            ClearMessage();
            lvList.VirtualListSize = 0;
            StackItems.Clear();
            StackItemsF.Clear();
            SetStatus(0);
        }
        #endregion

        #region 列表事件
        private void lvList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            e.Item = new ListViewItem(new string[] { StackItemsF[e.ItemIndex].ID, StackItemsF[e.ItemIndex].IDName, StackItemsF[e.ItemIndex].Name, StackItemsF[e.ItemIndex].StackNum });
        }
        private void lvList_Click(object sender, EventArgs e)
        {
            CheckAndSaveItem();

            if (lvList.SelectedIndices.Count > 0)
            {
                StackItem si = StackItemsF[lvList.SelectedIndices[0]];
                if (si.StackNum == "0")
                {
                    numEDStack.Enabled = false;
                }
                else
                {
                    numEDStack.Enabled = true;
                }
                tboxEID.Text = si.ID;
                tboxEIDName.Text = si.IDName;
                tboxEName.Text = si.Name;
                tboxESStack.Text = si.StackNum;
                tboxEType.Text = si.Stacktype.ToString();
                numEDStack.Value = Convert.ToDecimal(si.StackNum);
            }
        }

        #endregion

        #region 过滤
        private void tboxFilter_TextChanged(object sender, EventArgs e)
        {
            ShowData();
        }

        private void ckboxItems_CheckedChanged(object sender, EventArgs e)
        {
            ShowData();
        }

        private void ckboxBlocks_CheckedChanged(object sender, EventArgs e)
        {
            ShowData();
        }

        private void ckboxHaveStack_CheckedChanged(object sender, EventArgs e)
        {
            ShowData();
        }

        private void buttFilter_Click(object sender, EventArgs e)
        {
            tboxFilter.TextChanged -= tboxFilter_TextChanged;
            ckboxItems.CheckedChanged -= ckboxItems_CheckedChanged;
            ckboxBlocks.CheckedChanged -= ckboxBlocks_CheckedChanged;
            ckboxHaveStack.CheckedChanged -= ckboxHaveStack_CheckedChanged;
            tboxFilter.Clear();
            ckboxHaveStack.Checked = true;
            ckboxBlocks.Checked = true;
            ckboxItems.Checked = true;
            tboxFilter.TextChanged += tboxFilter_TextChanged;
            ckboxItems.CheckedChanged += ckboxItems_CheckedChanged;
            ckboxBlocks.CheckedChanged += ckboxBlocks_CheckedChanged;
            ckboxHaveStack.CheckedChanged += ckboxHaveStack_CheckedChanged;
            ShowData();
        }
        #endregion

        #region 加载与替换
        private void buttLoadShiftItems_Click(object sender, EventArgs e)
        {
            try
            {
                if (StackItems == null || StackItems.Count <= 0)
                {
                    MessageBox.Show("请先加载要修改的数据！");
                    return;
                }
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Items.xml|items.xml";
                if (ofd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                string tmp = "";
                Dictionary<string, string> dSS = StackAction.LoadStackNum(StackType.Item, ofd.FileName);

                if (MessageBox.Show("数据加载完成，是否替换？", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }

                foreach (StackItem item in StackItems)
                {
                    if (item.Stacktype != StackType.Item)
                    {
                        continue;
                    }
                    if (dSS.TryGetValue(item.IDName, out tmp))
                    {
                        if (item.StackNum == tmp)
                        {
                            continue;
                        }
                        else
                        {
                            item.StackNum = tmp;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                MessageBox.Show("替换完成！请手动保存！");


            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }

        private void buttLoadShiftBlocks_Click(object sender, EventArgs e)
        {
            try
            {
                if (StackItems == null || StackItems.Count <= 0)
                {
                    MessageBox.Show("请先加载要修改的数据！");
                    return;
                }
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Blocks.xml|blocks.xml";
                if (ofd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                string tmp = "";
                Dictionary<string, string> dSS = StackAction.LoadStackNum(StackType.Block, ofd.FileName);

                if (MessageBox.Show("数据加载完成，是否替换？", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }

                foreach (StackItem item in StackItems)
                {
                    if (item.Stacktype != StackType.Block)
                    {
                        continue;
                    }
                    if (dSS.TryGetValue(item.IDName, out tmp))
                    {
                        if (item.StackNum == tmp)
                        {
                            continue;
                        }
                        else
                        {
                            item.StackNum = tmp;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                MessageBox.Show("替换完成！请手动保存！");
            }
            catch(Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
        #endregion
    }
}
